package com.it.jasypt.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

public class SensitiveDataDynamicWithArgsSerializer extends StdSerializer<String> implements ContextualSerializer {
    private final String[] allowedRoles;
    private final Pattern maskPattern;
    private final String maskReplacement;

    // 通过构造函数接收注解参数
    public SensitiveDataDynamicWithArgsSerializer() {
        this(new String[0], "", ""); // 默认值
    }

    // 通过构造函数接收注解参数
    public SensitiveDataDynamicWithArgsSerializer(String[] allowedRoles, String maskPattern, String maskReplacement) {
        super(String.class);
        this.allowedRoles = allowedRoles;
        this.maskPattern = Pattern.compile(maskPattern);
        this.maskReplacement = maskReplacement;
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        // 获取当前用户权限
        // 从上下文获取当前用户数据 ThreadLocal
        Set<String> mockRoles = new HashSet<>(Arrays.asList("EDITOR", "VIEWER"));

        // 判断是否允许显示完整数据
        boolean shouldMask = Arrays.stream(allowedRoles).noneMatch(mockRoles::contains);
        if (shouldMask) {
            value = maskPattern.matcher(value).replaceAll(maskReplacement);
        }
        gen.writeString(value);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        SensitiveData ann = property.getAnnotation(SensitiveData.class);
        return new SensitiveDataDynamicWithArgsSerializer(ann.hasAnyRole(), ann.maskPattern(), ann.maskReplacement());
    }
}